package top.haijunit.work.controller.demo;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;
import top.haijunit.work.core.doamin.PageQuery;
import top.haijunit.work.core.doamin.Result;
import top.haijunit.work.core.doamin.ResultPage;
import top.haijunit.work.service.CacheTestService;

import java.util.Collection;

/**
 * 缓存测试
 *
 * @author zhanghaijun
 * @since 2024-09-05
 */
@Slf4j
@RestController
@RequestMapping("/test/cache")
@ApiSupport(order = 2)
@Tag(name = "测试缓存")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TestCacheController {

    private final CacheTestService cacheService;
    private final CacheManager cacheManager;

    @ApiOperationSupport(order = 1)
    @Operation(summary = "分页查询")
    @GetMapping("/page")
    public ResultPage<String> listPage(PageQuery pageQuery, String info) {
        return cacheService.selectPageList(pageQuery, info);
    }

    @ApiOperationSupport(order = 2)
    @Operation(summary = "列表查询")
    @GetMapping("/list")
    public Result<Collection<String>> list(String dto) {
        return Result.success(cacheService.selectList(dto));
    }

    @ApiOperationSupport(order = 4)
    @Operation(summary = "详情查询")
    @GetMapping("/detail/{code}")
    public Result<String> detail(@PathVariable("code") String code) {
        return Result.success(cacheService.selectDetail(code));
    }

    @ApiOperationSupport(order = 5)
    @Operation(summary = "新增")
    @PostMapping("/add")
    public Result<String> add(@RequestBody String str) {
        String code = cacheService.insert(str);
        return Result.success(code);
    }

    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除")
    @DeleteMapping("/delete/{code}")
    public Result<String> delete(@PathVariable String code) {
        return Result.success(cacheService.delete(code));
    }

    @ApiOperationSupport(order = 8)
    @Operation(summary = "清空缓存")
    @GetMapping("/clear")
    public Result<String> clear() {
        for (String name : cacheManager.getCacheNames()) {
            log.info("clear cache name: {}", name);
            Cache cache = cacheManager.getCache(name);
            if (cache != null) {
                cache.clear();
            }
        }
        return Result.success("ok");
    }
}
